//
//  NewsListViewController.m
//  suRead
//
//  Created by lidi on 15/11/6.
//  Copyright © 2015年 bao. All rights reserved.
//

#import "NewsListViewController.h"
#import "Masonry.h"
#import "MJRefresh.h"
#import "UIViewController+HUD.h"
#import "UIImageView+WebCache.h"
#import "ServiceNews.h"

#import "M_News.h"

#import "NewsCell.h"
#import "NewsImageCell.h"
#import "NewsFocusCell.h"
#import "NewsAdvCell.h"
#import "NewsOneOfImageCell.h"
#import "NewsQuestionCell.h"
#import "ZhuanTiCell.h"
#import "VideoShowCell.h"

#import "NewsDetailViewController.h"
#import "NewsAlbumViewController.h"
#import "NewsWebViewController.h"
#import "SpecialNewsListViewController.h"
#import "WenBaTagListController.h"
#import "WenBaDetailController.h"

#import <RongIMLib/RongIMLib.h>
#import "RCDLiveChatRoomViewController.h"
#import "RCDLiveChatRoomLSViewController.h"
#import "RCDLiveKitCommonDefine.h"
#import "AFNetworking.h"
#import <CommonCrypto/CommonDigest.h>
#import "AppDelegate.h"
#import "RCDLive.h"

#import "AccountManager.h"
#import "M_PlayNewsDetail.h"

#import "NewCellManager.h"
#import "NewFocusWordCell.h"
#import "NewsFocusImageCell.h"
#import "NewFocusNewsCell.h"

#import "NewsSpeechManager.h"
#import "MoreNewsViewController.h"

#define ScreenRectHeight [UIScreen mainScreen].applicationFrame.size.height
#define ScreenRectWidth [UIScreen mainScreen].applicationFrame.size.width

@interface NewsListViewController ()<UITableViewDataSource,UITableViewDelegate,NewsQuestionCellDelegate>
@property (nonatomic,strong)NSMutableArray *focusNews;
@property (nonatomic,strong)NSMutableArray *listNews;

@property (nonatomic,strong)UITableView *newsTableView;
@property (nonatomic,strong)NSURLSessionDataTask *requestHandle;
@property (nonatomic,assign)NSInteger currentPageIndex;

@property (nonatomic,strong)NSMutableDictionary *focusHandle;
@end

@implementation NewsListViewController

- (BOOL)isToutiao {
    return [self.subURL isEqualToString:@"index.php?m=app&c=index&a=toutiao"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    __weak typeof(self) weak_self = self;
    self.newsTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.newsTableView.backgroundColor = [UIColor whiteColor];
    self.newsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.newsTableView.delegate = self;
    self.newsTableView.dataSource = self;
    self.newsTableView.tableFooterView = [UIView new];
    [self.view addSubview:self.newsTableView];
    
    [self.newsTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weak_self.view).insets(UIEdgeInsetsZero);
    }];
    
    [NewCellManager registerCellFor:self.newsTableView];

    self.newsTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weak_self refreshData];
    }];
    
    self.newsTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weak_self loadMore];
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weak_self.newsTableView.mj_header beginRefreshing];
    });
}

- (void)refreshData
{
    self.currentPageIndex = 1;
    if (self.requestHandle) {
        [self.requestHandle cancel];
        self.requestHandle = nil;
    }
    [self.newsTableView.mj_footer resetNoMoreData];
    
    __weak typeof(self) weak_self = self;
    [ServiceNews doFetchNewsList:RequestType_Refresh subURL:self.subURL pageIndex:self.currentPageIndex pageSize:DEFAULT_PAGE_SIZE success:^(id responseObject, NSString *message) {
        
        NSArray *listNews_ = [responseObject objectForKey:@"list"];
        weak_self.listNews = [NSMutableArray array];
        if (listNews_) {
            [weak_self.listNews addObjectsFromArray:listNews_];
        }
        
        weak_self.focusNews = [NSMutableArray array];
        weak_self.focusHandle = [NSMutableDictionary dictionary];
        
        id focus = [responseObject objectForKey:@"focus"];
        if (focus && [focus isKindOfClass:[NSArray class]] && [focus count] > 0) {
            [weak_self.focusNews addObject:@{@"type":@"focus",@"content":focus}];
            
            NewsFocusCell *cell = [weak_self.newsTableView dequeueReusableCellWithIdentifier:@"NewsFocusCell"];
            cell.newsDatas = focus;
            cell.focusTapAtIndex = ^ (M_News *news) {
                //焦点图点击
                [NewCellManager jumpToNewsDetail:news wohs:self.wohs handle:self];
            };
            
            [weak_self.focusHandle setObject:cell forKey:@"focus"];
        }

        if ([self isToutiao]) {
            [ServiceNews doFetchHomeFocusList:^(id responseObject, NSString *message) {
                
                if (responseObject && [responseObject isKindOfClass:[NSArray class]]) {
                    for (NSInteger i = 0; i < [responseObject count]; i++) {
                        NSDictionary *item = [responseObject objectAtIndex:i];

                        
                        NSString *type = [item objectForKey:@"type"];
                        NSArray *content = [item objectForKey:@"content"];
                        
                        if ([type isEqualToString:@"word"]) {
                            //NewFocusWordCell
                            NewFocusWordCell *cell_ = [weak_self.newsTableView dequeueReusableCellWithIdentifier:@"NewFocusWordCell"];
                            cell_.newsDatas = content;
                            cell_.focusTapAtIndex = ^ (M_News *news) {
                                //焦点图点击
                                [NewCellManager jumpToNewsDetail:news wohs:self.wohs handle:self];
                            };
                            cell_.actionMore = ^ () {
                                MoreNewsViewController *controller = [MoreNewsViewController new];
                                controller.hidesBottomBarWhenPushed = YES;
                                [weak_self showViewController:controller sender:nil];
                            };
                            [weak_self.focusNews addObject:item];
                            [weak_self.focusHandle setObject:cell_ forKey:type];
                        }
                        
                        if ([type isEqualToString:@"spic"]) {
                            //NewFocusNewsCell
                            NewFocusNewsCell *cell_ = [weak_self.newsTableView dequeueReusableCellWithIdentifier:@"NewFocusNewsCell"];
                            cell_.newsDatas = content;
                            cell_.focusTapAtIndex = ^ (M_News *news) {
                                //焦点图点击
                                [NewCellManager jumpToNewsDetail:news wohs:self.wohs handle:self];
                            };
                            [weak_self.focusNews addObject:item];
                            [weak_self.focusHandle setObject:cell_ forKey:type];
                        }
                        
                        if ([type isEqualToString:@"bpic"]) {
                            //NewFocusImageCell
                            NewsFocusImageCell *cell_ = [weak_self.newsTableView dequeueReusableCellWithIdentifier:@"NewsFocusImageCell"];
                            cell_.newsDatas = content;
                            cell_.focusTapAtIndex = ^ (M_News *news) {
                                //焦点图点击
                                [NewCellManager jumpToNewsDetail:news wohs:self.wohs handle:self];
                            };
                            [weak_self.focusNews addObject:item];
                            [weak_self.focusHandle setObject:cell_ forKey:type];
                        }
                        
                        
                    }
                }
                
                [weak_self.newsTableView.mj_header endRefreshing];
                [weak_self.newsTableView reloadData];
            } failure:^(NSString *message) {
                [weak_self.newsTableView.mj_header endRefreshing];
                [weak_self.newsTableView reloadData];
            }];
        } else {
            [weak_self.newsTableView.mj_header endRefreshing];
            [weak_self.newsTableView reloadData];
        }
        
//        if ([listNews_ count]<DEFAULT_PAGE_SIZE) {
//            [weak_self.newsTableView.mj_footer endRefreshingWithNoMoreData];
//        }
        
    } failure:^(NSString *message) {
        [weak_self.newsTableView.mj_header endRefreshing];
    }];
    
}

- (void)loadMore
{
    self.currentPageIndex ++;
    if (self.requestHandle) {
        [self.requestHandle cancel];
        self.requestHandle = nil;
    }
    
    __weak typeof(self) weak_self = self;
    [ServiceNews doFetchNewsList:RequestType_LoadMore subURL:self.subURL pageIndex:self.currentPageIndex pageSize:DEFAULT_PAGE_SIZE success:^(id responseObject, NSString *message) {
        
        [weak_self.newsTableView.mj_footer endRefreshing];
        NSArray *listNews_ = [responseObject objectForKey:@"list"];
         if (listNews_) {
            [weak_self.listNews addObjectsFromArray:listNews_];
        }
        
        [weak_self.newsTableView reloadData];
        if ([listNews_ count] <=0 ) {
            [weak_self.newsTableView.mj_footer endRefreshingWithNoMoreData];
        }
        
    } failure:^(NSString *message) {
        [weak_self.newsTableView.mj_footer endRefreshing];
    }];
}

#pragma mark tableViewDatasouce Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (!section) {
        
        //其他轮播图
        if ([self.focusNews count] > 0 && self.wohs!=3) {
            return [self.focusNews count];
        }
        else {
            return 0;
        }
    }
    else {
        return [self.listNews count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!indexPath.section) {
        //焦点图
        NSString *type = [[self.focusNews objectAtIndex:indexPath.row] objectForKey:@"type"];
        return [self.focusHandle objectForKey:type];
    }
    else {
        return [NewCellManager cellForNews:self.listNews[indexPath.row] whos:self.wohs tableView:tableView];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!indexPath.section) {
        //焦点图
        NSDictionary *item = [self.focusNews objectAtIndex:indexPath.row];
        NSString *type = [item objectForKey:@"type"];
        if ([type isEqualToString:@"focus"]) {
            return ScreenRectWidth * 0.5f;
        }
        if ([type isEqualToString:@"word"]) {
            return 100.0f;
        }
        if ([type isEqualToString:@"spic"]) {
            return 100.0f;
        }
        if ([type isEqualToString:@"bpic"]) {
            return 80.0f;
        }
        return 0;
    }
    else
    {
        return [NewCellManager heightForNewsCell:self.listNews[indexPath.row] whos:self.wohs];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section) {
        M_News *news_ = [self.listNews objectAtIndex:indexPath.row];
        [NewCellManager jumpToNewsDetail:news_ wohs:self.wohs handle:self];
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }
}

- (void)speech {
    if (self.listNews && [self.listNews count] > 0) {
        [[NewsSpeechManager shared] speech:self.listNews];
    }
}

@end
